<%@ page language="java" import="java.util.*" contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="blog1.DBBean"%>
<%@ page import="blog1.UserBean"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="java.net.*"%>
<jsp:useBean id="myDBbean" class="blog1.DBBean"></jsp:useBean>
<jsp:useBean id="user" class="blog1.UserBean" scope="request"></jsp:useBean>
<jsp:setProperty name="user" property="*" />
<html>
  <head>
    <title>用户登录验证</title>
  </head>
  
  <body>
    <h2>用户登录验证</h2>
    <hr>
    <%
        request.setCharacterEncoding("utf-8");
        //首先判断用户是否选择记住密码
        String[] isUseCookies =request.getParameterValues("LoginForm[rememberMe]");
        if(isUseCookies!=null && isUseCookies.length>0)
        {
        	//把用户名和密码保存在Cookie对象里面
        	String username =URLEncoder.encode(request.getParameter("name"), "utf-8");
        	//使用URLEncoder解决cookie无法保存中文字符串的问题
        	String password =URLEncoder.encode(request.getParameter("password"), "utf-8");
        	
            Cookie usernameCookie =new Cookie("username",username);
            Cookie passwordCookie =new Cookie("password",password);
            usernameCookie.setMaxAge(864000);
            passwordCookie.setMaxAge(864000);//设置最大生存期限为十天，单位秒
            response.addCookie(usernameCookie);
            response.addCookie(passwordCookie);
        }
        else
        {
        	Cookie[] cookies = request.getCookies();
            if(cookies!=null && cookies.length>0)
            {
            	for(Cookie c:cookies)
            	{
            		if(c.getName().equals("username")||c.getName().equals("password"))
            		{
            			c.setMaxAge(0);//设置Cookie失效
            			response.addCookie(c);//重新保存
            		}
            	}
            }
        }
		//user对象中的userName和userPWD是通过自省完成赋值的
		String userName = user.getName();
		String userPwd = user.getPassword();
		String sql = "select * from user where name='"+userName+"' and password='"+userPwd+"';";
		if (user.isLogined()){
			out.println("您已经登录过了!");
		}else{
			ResultSet rs = myDBbean.query(sql);
			if (rs.next()){
				user.setLogined(true);
				//response.setHeader("refresh", "3;URL=user_index.jsp");				
					//out.println("恭喜您登录成功!三秒后自动跳转");
					//response.setHeader("refresh", "3;URL=user_index.jsp");	
					response.sendRedirect("user_index.jsp");
					 }else{
			%>
			
			    <script type="text/javascript" language="javascript">
			        alert("对不起，您的帐号或密码不正确!点击确定重新登录"); // 弹出错误信息
			        window.location='Login.jsp'; // 跳转到登录界面
	            </script>
			<%
						//user.setLogined(false);
						//out.println("对不起，您的帐号或密码不正确!");
				
					 }					
				 }			   	
	         %>
  </body>
</html>